import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Select,
	message,
	Cascader,
	TreeSelect,
	DatePicker,
	Tag,
} from 'antd'
import React, {useState, useEffect, memo, useRef} from 'react'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import {
	addInspection,
	editInspection,
	viewInspection,
	getCarPage,
} from '@/service/carMessage/inspection'
import {getCompany} from '@/service/system/company'
import {modelSeriesFun, translateDataToTree} from '@/utils/common/index'
import {getAllCitysPermission, getHolderDictInfo} from '@/service/common'
import {getXZCarTypeList} from '@/service/carMessage/list'
import {getAllSupplierAccessList} from '@/service/supplier/supplierAccess'
import {getAllParking} from '@/service/storage/archives'

import CustomTable from '@/components/Table'
import {integerPatternJust} from '@/utils/common/validator'
import {licenseProperty} from '../../dict'
import 'moment/locale/zh-cn'

const {Panel} = Collapse

const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

const inspectionView = memo(
	(props: {
		user: {
			userId: string
			userName: string
			orgId: string | number
			permissionID: any
		}
		location: any
	}) => {
		const {orgId, permissionID} = props.user
		const [params, setParams] = useState({
			current: 1,
			size: 10,
		})
		const [total, setTotal] = useState(0)
		const [tableList, setTableList] = useState<any[]>([])

		const [type, setType] = useState<string>()
		const [form] = Form.useForm<any>()

		const [inspectionId, setInspectionId] = useState()
		const [orgSource, setOrgSource] = useState<any>([])
		const [citysList, setCitysList] = useState([])
		const [carTypeList, setCarTypeList] = useState<any>([])
		const [supplierList, setSupplierList] = useState<any>([])
		const [allParking, setAllParking] = useState<any>([])
		const [otherData, setOtherData] = useState<any>()
		// 持有方数据
		const [holderDict, setHolderDict] = useState([])
		/** 获取持有方数据 */
		const getHolderDictInfoFun = () => {
			getHolderDictInfo({type: 'holder'}).then((res: any) => {
				if (res?.success) {
					setHolderDict(res?.data)
				}
			})
		}

		// 获取品牌车系
		const onCarTypeListFun = () => {
			getXZCarTypeList().then((res: any) => {
				if (res?.success) {
					setCarTypeList(modelSeriesFun(res.data))
				}
			})
		}

		useEffect(() => {
			onCarTypeListFun()
			getHolderDictInfoFun()
		}, [])

		// 初始化-城市
		const getCitysFun = (newOrgId: string, ctype: boolean) => {
			const d = {
				permission: permissionID,
				newOrgId,
			}
			getAllCitysPermission(d).then((res: any) => {
				if (res?.success) {
					setCitysList(() => res.data)
					if (ctype) {
						form.setFieldsValue({cityId: null})
					}
				}
			})
		}

		useEffect(() => {
			getCitysFun('', false)
		}, [orgId])

		/** 获取供应商列表 */
		const supplierAccessListFun = () => {
			getAllSupplierAccessList().then((res: any) => {
				if (res?.success) {
					setSupplierList(() => res.data)
				}
			})
		}

		useEffect(() => {
			supplierAccessListFun()
		}, [])

		/** 获取请车厂列表 */
		const allParkingFun = (
			newOrgId: string,
			cityId: string,
			ctype: boolean,
		) => {
			const d = {
				permission: permissionID,
				newOrgId,
				cityId,
				warehouseType: 1,
			}
			getAllParking(d).then((res: any) => {
				if (res?.success) {
					setAllParking(() => res.data)
					if (ctype) {
						form.setFieldsValue({parkingId: null})
					}
				}
			})
		}

		useEffect(() => {
			allParkingFun('', '', false)
		}, [])

		// 获取组织机构数据
		const onOrgFun = () => {
			getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
				if (res?.success) {
					const list: any = translateDataToTree(res?.data)
					setOrgSource(list as any)
				}
			})
		}

		useEffect(() => {
			onOrgFun()
		}, [props?.user?.orgId])

		// 初始化-详情数据
		const getView = (id: string) => {
			viewInspection({id}).then((res: any) => {
				if (res?.success) {
					form.setFieldsValue({
						...res.data,
						warehouseTime: res?.data?.warehouseTime
							? moment(res?.data?.warehouseTime)
							: '',
					})
					const data = {
						parkingName: res?.data?.parkingName,
						supplyName: res?.data?.supplyName,
						fullName: res?.data?.fullName,
						holderName: res?.data?.holderName,
						companyName: res?.data?.companyName,
						parentCityId: res?.data?.parentCityId,
						cityId: res?.data?.cityId,
						cityName: res?.data?.cityName,
					}
					setOtherData(() => data)
				}
			})
		}

		// 初始化-详情数据
		const getCarList = () => {
			const {id} = props.location.query
			getCarPage({bareId: id, ...params}).then((res: any) => {
				if (res?.success) {
					setTableList(() => res?.data?.records)
					setTotal(res?.data?.total)
				}
			})
		}

		// 自定义一个初始不更新的hook
		const useUpdateEffect = (fn: Function, inputs: any[]) => {
			const didMountRef = useRef(false)
			useEffect(() => {
				if (didMountRef.current) fn()
				else didMountRef.current = true
			}, inputs)
		}

		// 使用自定义hook
		useUpdateEffect(getCarList, [params])

		// 根据路由判断当前页面状态
		useEffect(() => {
			const {id} = props.location.query
			if (id) {
				getView(id)
				setInspectionId(id)
				getCarList()
			}
			const hrefs = window.location.href
			if (hrefs.includes('add')) {
				setType('add')
			} else if (hrefs.includes('edit')) {
				setType('edit')
			} else {
				setType('view')
			}
		}, [])

		// 保存
		const onSubmit = async () => {
			const formData = await form.validateFields()
			if (inspectionId) {
				editInspection({
					id: inspectionId,
					...formData,
					...otherData,
					warehouseTime: moment(formData?.warehouseTime).format(
						'YYYY-MM-DD HH:mm:ss',
					),
				})
					.then((res) => {
						if (res.success) {
							message.success(res.msg)
							history.goBack()
						}
					})
					.catch((err) => {
						message.error(err)
					})
			} else {
				addInspection({
					...formData,
					...otherData,
					warehouseTime: moment(formData?.warehouseTime).format(
						'YYYY-MM-DD HH:mm:ss',
					),
				})
					.then((res) => {
						if (res.success) {
							message.success(res.msg)
							history.goBack()
						}
					})
					.catch((err) => {
						message.error(err)
					})
			}
		}

		// 列表
		const columns: any = [
			{
				title: '序号',
				dataIndex: 'order',
				align: 'center',
				width: 70,
				render(text: any, record: any, index: any) {
					return <span>{(params.current - 1) * 10 + index + 1}</span>
				},
			},
			{
				title: '车架号',
				dataIndex: 'vin',
				align: 'center',
				width: 140,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '发动机号',
				dataIndex: 'engineNumber',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '品牌车系车型',
				dataIndex: 'carBrandSeries',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '车辆性质',
				dataIndex: 'carProperty',
				align: 'center',
				width: 200,
				render: (text: number) => (
					<>
						{licenseProperty?.map(
							(item: {key: number; label: string}) => {
								if (item?.key === text) {
									return (
										<Tag color="processing">
											{item?.label}
										</Tag>
									)
								}
								return ''
							},
						)}
					</>
				),
			},
			{
				title: '颜色',
				dataIndex: 'colorName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '持有方',
				dataIndex: 'holderName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},

			{
				title: '所属公司',
				dataIndex: 'companyName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '入库城市',
				dataIndex: 'cityName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '停车场',
				dataIndex: 'parkingName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '生产日期',
				dataIndex: 'productionTime',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
		]
		// 供应商名称变化
		const onSupplierChange = (value: string, option: any) => {
			setOtherData({...otherData, supplyName: option?.supplierName})
		}

		// 品牌车系车型变化
		const onFashionChange = (value: string, option: any) => {
			setOtherData({...otherData, fashionName: option?.fullName})
		}

		// 持有方名称变化
		const onHolderChange = (value: string, key: any) => {
			setOtherData({...otherData, holderName: key?.valueName})
		}

		// 所属公司变化
		const onOrgChange = (value: string, option: any) => {
			setOtherData({...otherData, companyName: option[0]})
			getCitysFun(value, true)
			allParkingFun(value, '', true)
		}

		// 城市变化
		const onCitysChange = (value: any, selectedOptions: any) => {
			if (value) {
				setOtherData({
					...otherData,
					parentCityId: selectedOptions[0].id,
					cityId: selectedOptions[1].id,
					cityName: selectedOptions[1].name,
				})
				const newOrgId = form.getFieldValue('orgId')
				allParkingFun(newOrgId, selectedOptions[1].id, true)
			}
		}

		// 停车场变化
		const onParkingChange = (value: string, option: any) => {
			setOtherData({...otherData, parkingName: option?.warehouseName})
		}

		return (
			<div className={styles.admittanceAdd}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					<Collapse
						defaultActiveKey={['1', '2']}
						ghost
						expandIconPosition="end">
						<Panel header={customizeHeader('基础信息')} key="1">
							<Form
								form={form}
								name="basic"
								layout="horizontal"
								labelCol={{flex: '120px'}}
								labelAlign="right"
								labelWrap
								initialValues={{remember: true}}
								autoComplete="off"
								disabled={type === 'view'}>
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="供应商名称"
											name="supplyId"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<Select
												placeholder="请选择"
												fieldNames={{
													value: 'id',
													label: 'supplierName',
												}}
												options={[...supplierList]}
												onChange={onSupplierChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="招标编号"
											name="biddingNo"
											rules={[
												{
													required: true,
													message: '请输入',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={60}
											/>
										</Form.Item>
									</Col>

									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购申请单号"
											name="purchaseNo"
											rules={[
												{
													required: true,
													message: '请输入',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={60}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="合同编号"
											name="contractNo"
											rules={[
												{
													required: true,
													message: '请输入',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={60}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="品牌车系车型"
											name="fashionId"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<Select
												placeholder="请选择"
												fieldNames={{
													value: 'id',
													label: 'fullName',
												}}
												options={[...carTypeList]}
												onChange={onFashionChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="车辆性质"
											name="carProperty"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<Select
												placeholder="请选择"
												fieldNames={{
													value: 'key',
													label: 'label',
												}}
												options={[...licenseProperty]}
												onChange={onFashionChange}
											/>
										</Form.Item>
									</Col>

									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="持有方"
											name="holderId"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<Select
												placeholder="请选择"
												fieldNames={{
													value: 'value',
													label: 'valueName',
												}}
												options={[...holderDict]}
												onChange={onHolderChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="所属公司"
											name="orgId"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<TreeSelect
												showSearch
												style={{width: '100%'}}
												dropdownStyle={{
													maxHeight: 400,
													overflow: 'auto',
												}}
												placeholder="请选择"
												allowClear
												treeDefaultExpandAll
												fieldNames={{
													label: 'name',
													value: 'id',
												}}
												treeDataSimpleMode
												treeData={[...orgSource]}
												onChange={onOrgChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="入库城市"
											name="cityId"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<Cascader
												fieldNames={{
													label: 'name',
													value: 'id',
													children: 'cityInfoList',
												}}
												options={citysList}
												placeholder="请选择"
												onChange={onCitysChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="停车场"
											name="parkingId"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<Select
												placeholder="请选择"
												fieldNames={{
													value: 'id',
													label: 'warehouseName',
												}}
												options={[...allParking]}
												onChange={onParkingChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="入库数量"
											name="warehouseNum"
											rules={[
												{
													required: true,
													pattern: integerPatternJust,
													message: '请输入正整数',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={10}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="入库时间"
											name="warehouseTime"
											rules={[
												{
													required: true,
													message: '请选择',
												},
											]}>
											<DatePicker
												placeholder="请选择"
												showTime
												format="YYYY-MM-DD  HH:mm:ss"
											/>
										</Form.Item>
									</Col>
								</Row>
							</Form>
							<div className="table">
								{type !== 'add' ? (
									<CustomTable
										params={params}
										columns={columns}
										pagination
										total={total}
										callback={(pagination: any) => {
											setParams(pagination)
										}}
										loading={false}
										dataSource={tableList}
									/>
								) : null}
							</div>
						</Panel>
					</Collapse>
					<div className={styles.wrap}>
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							取消
						</Button>
						{type !== 'view' ? (
							<Button
								type="primary"
								htmlType="submit"
								onClick={onSubmit}>
								保存
							</Button>
						) : (
							''
						)}
					</div>
				</div>
			</div>
		)
	},
)
export default connect(({user}: any) => ({user}))(inspectionView)
